package com.whccb.apps.office.document.event.receive;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListenerInterface;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.HistoryTaskInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.commons.pagination.SQLPagination;
import com.actionsoft.bpms.org.cache.DepartmentCache;
import com.actionsoft.bpms.org.cache.UserCache;
import com.actionsoft.bpms.org.model.DepartmentModel;
import com.actionsoft.bpms.org.model.UserModel;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.ODConstant;
import com.whccb.apps.office.document.util.ODAppUtil;

public class ChairmanOpinionToSubProcessAndNoticeAfterFormSaveEvent_bak extends
		ExecuteListener implements ExecuteListenerInterface {

	public String getDescription() {
		return "收文流程中，文书岗根据董事长批示意见决定增加或删除会签分支，"
				+ "并代录入董事长批示后，将相关批示信息反写回对应子流程中，给相关会签人员发出通知提醒。";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	@Override
	public void execute(ProcessExecutionContext pec) throws Exception {
		BO swBo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_RECEIVE",
				pec.getProcessInstance().getId());
		String receive = "";
		if (swBo != null) {
			List<ProcessInstance> subProcessList = SDK.getProcessAPI().query()
					.parentProcessInstId(pec.getProcessInstance().getId())
					.list();
			String chairmanOption = swBo.getString("CHAIRMAN");
			String doUseridStr = swBo.getString("DOUSERID");
			if (StringUtils.isNotEmpty(doUseridStr)) {
				String[] doUserids = doUseridStr.split(",");
				if (doUserids != null && doUserids.length > 0) {
					// 查询出该收文流程对应的子流程
					for (String doUserid : doUserids) {
						if (StringUtils.isNotEmpty(doUserid)) {
							// 检查所有子流程中是否有该启动者，没有表示是新增的，则需要创建
							boolean isCreateSub = true;
							if (subProcessList != null
									&& !subProcessList.isEmpty()
									&& subProcessList.size() > 0) {
								for (ProcessInstance subProcess : subProcessList) {
									if (subProcess != null) {
										if (doUserid.equals(subProcess
												.getCreateUser())) {
											isCreateSub = false;
											BO swDoBo = SDK
													.getBOAPI()
													.getByProcess(
															"BO_WHBK_OD_RECEIVE_DO",
															subProcess.getId());
											if (swDoBo != null) {
												swDoBo.set("CHAIRMAN",
														chairmanOption);
												SDK.getBOAPI()
														.updateByBindId(
																"BO_WHBK_OD_RECEIVE_DO",
																swDoBo.getBindId(),
																"CHAIRMAN",
																chairmanOption);
												// 再更新签批附件
												SDK.getBOAPI().removeFiles(
														swDoBo.getId(),
														"CHAIRMANPDF");
												SDK.getBOAPI()
														.copyFileTo(
																swBo.getId(),
																"CHAIRMANPDF",
																swDoBo.getId(),
																"BO_WHBK_OD_RECEIVE_DO",
																"CHAIRMANPDF",
																swDoBo.getBindId(),
																null);
												if (StringUtils
														.isNotEmpty(chairmanOption)) {
													sendNotify(
															subProcess.getId(),
															swDoBo);
												}
											}
											subProcessList.remove(subProcess);
											break;
										}
									}
								}
							}
							// 循环完毕
							if (isCreateSub) {// 所有子流程的启动者都不是该帐号，说明是新增的子流程
								String thisReceive = addsub(
										pec.getUserContext().getSessionId(),
										swBo,
										pec.getProcessInstance().getId(),
										ODConstant.OD_SW_PARENT_SUBPROCESS_TASKDEFID,
										doUserid);
								if (StringUtils.isNotEmpty(thisReceive)) {
									receive = receive + "&" + thisReceive;
								}
							}
						}
					}
				}
			}

			if (subProcessList != null && !subProcessList.isEmpty()
					&& subProcessList.size() > 0) {// 剩下的是需要删除的分支
				for (ProcessInstance subProcess : subProcessList) {
					if (subProcess != null) {
						SDK.getProcessAPI().delete(subProcess,
								pec.getUserContext());
					}

				}

			}
		}
		if (StringUtils.isNotEmpty(receive)) {
			throw new BPMNError("wsyh-01", receive);
		}
	}

	private void sendNotify(String subBinid, BO swBo) {
		if (StringUtils.isNotEmpty(subBinid) && swBo != null) {
			// 得到子流程的第一节点办理人，即为任务提醒人
			String notifyUserid = "";
			String subTaskId = "";
			List<TaskInstance> taskList = SDK.getTaskAPI().query()
					.activityDefId(ODConstant.SWBL_TASK_DEFID)
					.processInstId(subBinid).list();
			if (taskList != null && !taskList.isEmpty() && taskList.size() > 0) {
				notifyUserid = taskList.get(0).getTarget();
				subTaskId = taskList.get(0).getId();
			} else {
				List<HistoryTaskInstance> taskHisList = SDK.getTaskAPI()
						.queryHistory()
						.activityDefId(ODConstant.SWBL_TASK_DEFID)
						.processInstId(subBinid).list();
				if (taskHisList != null && !taskHisList.isEmpty()
						&& taskHisList.size() > 0) {
					notifyUserid = taskHisList.get(0).getTarget();
					subTaskId = taskHisList.get(0).getId();
				}
			}

			// 发送通知
			JSONObject json = new JSONObject();
			StringBuffer notifycontent = new StringBuffer();
			notifycontent.append("来文机构:").append(swBo.getString("RECEIVEORG"))
					.append(",文号为：").append(swBo.getString("FILENUM"))
					.append("的收文流程，董事长有最新的批示，请及时查阅！");
			json.put("notifycontent", notifycontent.toString());
			json.put("bindid", subBinid);
			json.put("taskid", subTaskId);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("sender", "admin");
			params.put("targetIds", notifyUserid);
			params.put("content", json.toString());
			params.put("systemName", ODConstant.NOTIFY_SYSNAME);
			ODAppUtil.sendOfficeDocumentNotification(params);
		}
	}

	/**
	 * 收文流程在主流程中主动增加子流程分支
	 * 
	 */
	public String addsub(String sid, BO parentBo, String parentProcessinstid,
			String parentTaskDefid, String useridstr) {
		String backMessage = "";
		String queryCallActivityTaskInstId = "select ID from WFC_TASK where PROCESSINSTID = :PROCESSINSTID and ACTIVITYDEFID = :ACTIVITYDEFID ";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("PROCESSINSTID", parentProcessinstid);
		params.put("ACTIVITYDEFID", parentTaskDefid);
		String callActivityTaskInstId = DBSql.getString(SQLPagination
				.getPaginitionSQL(queryCallActivityTaskInstId, 0, 1), "ID",
				params);

		if (StringUtils.isNotEmpty(callActivityTaskInstId)) {
			if (StringUtils.isNotEmpty(useridstr)) {
				String[] userids = useridstr.split(",");
				for (String userid : userids) {
					if (StringUtils.isNotEmpty(userid)
							&& UserCache.getModel(userid) != null) {

						UserModel user = UserCache.getModel(userid);
						DepartmentModel dept = DepartmentCache.getModel(user
								.getDepartmentId());
						ProcessInstance subProcessInst = SDK.getProcessAPI()
								.createSubProcessInstance(userid, "追加收文办理流程",
										callActivityTaskInstId, null);
						// 同步BO数据
						SDK.getBOAPI()
								.query("BO_WHBK_OD_RECEIVE", true)
								.addQuery("BINDID =", parentProcessinstid)
								.copyTo("BO_WHBK_OD_RECEIVE_DO",
										subProcessInst.getId())
								.removeMapping("HQ").removeMapping("DOFILE")
								.exec();

						SDK.getProcessAPI().start(subProcessInst);
						BO subBo = SDK.getBOAPI()
								.getByProcess("BO_WHBK_OD_RECEIVE_DO",
										subProcessInst.getId());
						// 将填加的账户同步加至主流程的会签经理
						if (parentBo != null) {
							// 同步处理签批信息
							// 构建父流程的签批DC，将其复制到子流程相应位置。
							String parentDCGroupValue = parentBo.getBindId();
							String parentDCFileValue = parentBo.getId();
							String subDCGroupValue = subBo.getBindId();
							String subDCFileValue = subBo.getId();

							String leaderStr = parentBo.getString("LEADERSIGN");

							// 手写签批改了存储方式，此处需要修改

						}
						// backMessage = "添加成功，请通过跟踪图并刷新页面查看";
					} else {
						backMessage = useridstr + "帐号不合法";
					}
				}
			} else {
				backMessage = useridstr + "帐号为空";
			}
		} else {
			backMessage = "当前所有收文办理子流程已经结束，不允许增加分支，" + useridstr + "的任务增加失败。";
		}
		return backMessage;
	}

}
